<template>
  <el-dialog
    v-el-drag-dialog
    :title="type === 'add' ? '添加机构' : '编辑机构'"
    :visible.sync="visible"
    width="600px"
    @closed="reset"
  >
    <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="90px">
      <el-form-item label="上级机构:">
        <el-input v-model="parentOrg" disabled />
      </el-form-item>
      <el-form-item label="机构编码:" prop="orgCode">
        <el-input v-model.trim="temp.orgCode" placeholder="手工输入或自动产生" :maxlength="20" :disabled="type === 'edit'" :style="type === 'add' ? 'width: 300px' : null" clearable />
        <el-button v-if="type === 'add'" type="primary" size="small" plain @click.prevent="getOrgCode">获取</el-button>
      </el-form-item>
      <el-form-item label="机构名称:" prop="orgName">
        <el-input v-model="temp.orgName" clearable />
      </el-form-item>
      <el-form-item label="机构类型:" prop="orgType">
        <el-select v-model="temp.orgType" :loading="$loadingPlugin.queryOptionsMap" style="width: 200px;" @change="orgTypeChange">
          <el-option
            v-for="item in orgTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
        <el-checkbox v-show="temp.orgType === 11" v-model="checked" style="margin-left: 20px;">移动门市</el-checkbox>
      </el-form-item>
      <el-form-item>
        <label slot="label">坐标:</label>
        <coordinate v-model="temp.point" />
      </el-form-item>
      <el-form-item label="所在区域:" prop="address">
        <el-cascader v-if="visible" ref="cascader" v-model="temp.address" style="width: 100%;" :props="addressProps" clearable />
      </el-form-item>
      <el-form-item label="显示顺序:" prop="showIndex">
        <el-input-number v-model="temp.showIndex" :min="1" clearable />
      </el-form-item>
      <el-form-item label="备注:" prop="remark">
        <el-input v-model.trim="temp.remark" type="textarea" maxlength="255" show-word-limit />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import clonedeep from 'lodash.clonedeep'
  import Coordinate from '@/components/Coordinate'
  import { queryOrgCode, organizationAdd, queryMap, selectAreaCode } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { treeToArray } from '@/utils/jsonTree'

  export default {
    name: 'addOrganization',
    components: {
      Coordinate
    },
    props: {
      treeData: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        orgTypeMap: [],
        orgTypeList: [],
        type: 'add',
        currentOrgName: '',
        parentOrgName: '',
        checked: false,
        temp: {
          orgCode: '',
          orgName: '',
          orgType: '',
          point: null,
          address: [],
          showIndex: 999,
          remark: ''
        },
        rules: {
          orgName: [{ required: true, message: '请输入机构名称', trigger: 'change' }]
        },
        addressProps: {
          lazy: true,
          lazyLoad(node, resolve) {
            const { level, value } = node
            mergeAsyncFunc(selectAreaCode, { areaCode: value || 0 }).then((res) => {
              const nodes = res.data.map(item => ({
                value: item.areaCode,
                label: item.areaName,
                leaf: level >= 3
              }))
              resolve(nodes)
            })
          }
        }
      }
    },
    computed: {
      renderTreeData() {
        if (!this.temp.id && this.temp.id !== 0) return this.treeData
        const setDisable = (arr, isDisable) => {
          const list = clonedeep(arr)
          list.forEach(item => {
            if (isDisable || item.id === this.temp.id) {
              item.disabled = true
              if (item.children && item.children.length > 0) {
                item.children = setDisable(item.children, true)
              }
            } else {
              if (item.children && item.children.length > 0) {
                item.children = setDisable(item.children)
              }
            }
          })
          return list
        }
        return setDisable(this.treeData)
      },
      parentOrg() {
        return this.type === 'add' ? this.currentOrgName : this.parentOrgName
      }
    },
    created() {
      this.queryOptionsMap()
    },
    methods: {
      open(temp, type) {
        const org = treeToArray(this.treeData).find(item => item.orgId === temp.parentId)
        if (org) {
          this.parentOrgName = org.orgName
        } else {
          this.parentOrgName = '无'
        }
        this.currentOrgName = temp.orgName
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.type = type
          if (type === 'add') {
            this.temp.parentId = temp.orgId
          }
          if (type === 'edit') {
            this.temp = Object.assign(this.temp, temp, {
              address: [temp.provinceCode, temp.cityCode, temp.countryCode, temp.streetCode]
            })
            if (temp.lon && temp.lat) {
              this.temp.point = { lng: temp.lon, lat: temp.lat }
            }
            if (temp.orgOption) this.checked = (temp.orgOption & 0x01) > 0
          }
        })
      },
      // 查询枚举
      async queryOptionsMap() {
        const res = await queryMap({ enumName: 'OrgType' })
        this.orgTypeMap = res.data // 用户类型
        if (res.data.length > 0) this.temp.orgType = res.data[0].value
      },
      // 获取机构编码
      async getOrgCode() {
        const res = await queryOrgCode({
          codeType: 5
        })
        this.temp.orgCode = res.data
      },
      // 机构类型选择门市
      async orgTypeChange(value) {

      },
      async success() {
        const valid = await this.$refs.dataForm.validate()
        if (!valid) return
        if (this.type === 'add') {
          this.add()
        } else {
          this.edit()
        }
      },
      _getQuery() {
        const query = {
          orgCode: this.temp.orgCode,
          orgName: this.temp.orgName,
          orgType: this.temp.orgType,
          showIndex: this.temp.showIndex,
          remark: this.temp.remark
        }
        const address = this.$refs.cascader.getCheckedNodes()[0]
        if (address) {
          const pathNodes = address.pathNodes
          query.provinceName = pathNodes[0].label
          query.provinceCode = pathNodes[0].value
          query.cityName = pathNodes[1].label
          query.cityCode = pathNodes[1].value
          query.countryName = pathNodes[2].label
          query.countryCode = pathNodes[2].value
          query.streetName = pathNodes[3].label
          query.streetCode = pathNodes[3].value
        } else {
          query.provinceName = ''
          query.provinceCode = ''
          query.cityName = ''
          query.cityCode = ''
          query.countryName = ''
          query.countryCode = ''
          query.streetName = ''
          query.streetCode = ''
        }
        if (this.temp.point) {
          query.lon = this.temp.point.lng
          query.lat = this.temp.point.lat
        }
        if (this.temp.parentId || this.temp.parentId === 0) query.parentId = this.temp.parentId
        if (this.temp.orgId) query.orgId = this.temp.orgId
        if (this.temp.orgType === 11) {
          if (this.checked) {
            query.orgOption |= 1
          } else {
            query.orgOption |= 0
          }
        }
        return query
      },
      async add() {
        await organizationAdd(this._getQuery())
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '添加成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit() {
        await organizationAdd(this._getQuery())
        this.resolve(this._getQuery())
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.type = 'add'
        this.temp = {
          orgCode: '',
          orgName: '',
          orgType: '',
          point: null,
          address: [],
          showIndex: 999,
          remark: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .tree-select /deep/ .el-tree-select-input {
    width: 100%;
  }
</style>
